package com.study.controller;

import com.study.exception.CustomException;
import com.study.pojo.Result;
import com.study.pojo.Users;
import com.study.service.UsersService;
import com.study.utils.JwtUtil;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@RestController
public class UsersController {

    @Autowired
    private UsersService usersService;

    // 获取验证码
    @GetMapping("/getCode")
    public Result<String> captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //图片加数字模式
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);
        String code = captcha.text().toLowerCase();
        //创建ByteArrayOutputStream来保存验证码图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        captcha.out(outputStream);

        //将图片转换为Base64字符串
        byte[] imageBytes = outputStream.toByteArray();
        String base64Image = "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);
        //获取Session
        HttpSession session = request.getSession();

        //存入Session，设置12小时过期
        session.setAttribute("captcha", code);
        session.setAttribute("captcha_expire", System.currentTimeMillis() + 1000 * 60 * 60 * 12);
        session.setMaxInactiveInterval(1000 * 60 * 60 * 12);// 12小时过期

        System.out.println("验证码：" + code);
//        throw new CustomException("400", "获取验证码失败");

        return Result.success(base64Image);
    }

    // 获取所有用户
    @PostMapping("/selectAll")
    public Result<List<Users>> selectAll() {
        List<Users> list = usersService.selectAll();
        return Result.success(list);
    }

    // 注册
    @PostMapping("/register")
    public Result<String> register(@RequestBody Users users) {
        usersService.register(users);
        return Result.success("注册成功");
    }

    // 登录
    @PostMapping("/login")
    public Result<String> login(@RequestBody Users users, HttpSession session) {
        // 校验验证码
        String captcha = (String) session.getAttribute("captcha"); // 从Session中获取验证码
        Long captchaExpire = (Long) session.getAttribute("captcha_expire"); // 从Session中获取验证码过期时间

        //校验验证码是否有值
        if(captcha==null||captchaExpire==null){
            session.removeAttribute("captcha");
            session.removeAttribute("captcha_expire");
            throw new CustomException("500", "验证码不存在！");
        }

        // 校验验证码是否过期
        if (captchaExpire == null || Long.parseLong(String.valueOf(captchaExpire)) < System.currentTimeMillis()) {
            throw new CustomException("500", "验证码过期！");
        }

        // 校验验证码是否错误
        if (captcha == null || !captcha.equals(users.getCode())) {
            throw new CustomException("500", "验证码错误！");
        } else {
            //校验通过，移除Session中的验证码和失效时间
            session.removeAttribute("captcha");
            session.removeAttribute("captcha_expire");
        }

        String token = usersService.login(users);
        return Result.success(token);
    }

    // 获取当前登录用户信息
    @PostMapping("/getUserInfo")
    public Result<Users> getUserInfo(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        // 解析token获取用户信息
        Map<String, Object> claims = JwtUtil.parseToken(token);
        // 从claims中获取用户名
        String username = (String) claims.get("username");
        // 根据用户名查询用户信息
        Users user = usersService.findUserByUsername(username);
        return Result.success(user);
    }

    // 修改用户信息
    @PostMapping("/updateUserInfo")
    public Result<String> updateUserInfo(@Valid @RequestBody Users users) {
        usersService.updateUserInfo(users);
        return Result.success("修改成功");
    }
}
